package com.xj.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

/**
 *字符串操作功能类.
 *<P>
 *最后更新：2003-09-01
 *@author 王杰
 */
public class StringUtil
{
	/**
	 *字符串替换函数

	 *@param strSource 被替换的源字符串
	 *@param strFrom 要查找并替换的子字符串

	 *@param strTo 要替换为的子字符串

	 *@return 替换完成的字符串
	 */
	public static String replace(String strSource,String strFrom,String strTo)
	{
		String strDest = "";
		int intFromLen = strFrom.length();
		int intPos;
		
		if (strFrom == "") return strSource;
		while ((intPos = strSource.indexOf(strFrom)) != -1)
		{
			strDest = strDest + strSource.substring(0, intPos);
			strDest = strDest + strTo;
			strSource = strSource.substring(intPos + intFromLen);
		}
		strDest = strDest + strSource;
		return strDest;
	}
	
	/**
     *将普通字符串格式化成数据库认可的字符串格式

     *@param input 要格式化的字符串
     *@return 合法的数据库字符串

     */
    public static String toSql(String input) 
    {
        return input.replaceAll("'", "''");
	}
	
	/**
	 *截取字符串左侧指定长度的字符串

	 *@param input 输入字符串

	 *@param count 截取长度
	 *@return 截取字符串

	 */
    public static String left(String input, int count) 
    {
    	if ((input == null) || (input.length() == 0)) return "";
    	count = (count > input.length()) ? input.length() : count;
        return input.substring(0, count);
	}

	/**
	 *截取字符串右侧指定长度的字符串

	 *@param input 输入字符串

	 *@param count 截取长度
	 *@return 截取字符串

	 */
    public static String right(String input, int count)
    {
    	if ((input == null) || (input.length() == 0)) return "";
    	count = (count > input.length()) ? input.length() : count;
        return input.substring(input.length() - count, input.length());
	}

	/**
	 *从指定位置开始截取指定长度的字符串

	 *@param input 输入字符串

	 *@param index 截取位置，左侧第一个字符索引值是1
	 *@param count 截取长度
	 *@return 截取字符串

	 */
    public static String middle(String input, int index, int count) 
    {
    	if ((input == null) || (input.length() == 0)) return "";
    	count = (count > input.length() - index + 1) ? input.length() - index + 1 : count;
        return input.substring(index - 1, index + count - 1);
	}
	
	/**
	 *Unicode转换成GBK字符集

	 *@param input 待转换字符串
	 *@return 转换完成字符串

	 */
	public static String UnicodeToGB(String input) 
	{
		try 
		{
			if ((input == null) || (input.length() == 0)) 
			{
				return "";
			}
			else
			{
				String s1 = null;
				s1 = new String(input.getBytes("ISO8859_1"), "GBK");
				return s1;
			}
		}catch(Exception e) 
		{
			throw new RuntimeException(e.toString());
		}
	}

	/**
	 *GBK转换成Unicode字符集

	 *@param input 待转换字符串
	 *@return 转换完成字符串

	 */
	public static String GBToUnicode(String input) 
	{
		try 
		{
			if ((input == null) || (input.length() == 0)) 
			{
				return "";
			} 
			else 
			{
				String s1 = null;
				s1 = new String(input.getBytes("GBK"), "ISO8859_1");
				return s1;
			}
		}catch(Exception e) 
		{
			throw new RuntimeException(e.toString());
		}
	}
	
	/**
	 *分隔字符串成数组.
	 *<P>
	 *使用StringTokenizer，java.lang.String的split不能分隔逗号
	 *@param input 输入字符串

	 *@param delim 分隔符

	 *@return 分隔后数组

	 */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static String[] splitString(String input, String delim)
    {
        if(input == null || input.length() == 0) return new String[0];
        Vector vector = new Vector();
        for(StringTokenizer stringtokenizer = new StringTokenizer(input, delim); stringtokenizer.hasMoreTokens(); vector.addElement(stringtokenizer.nextToken()));
        String result[] = new String[vector.size()];
        for(int i = 0; i < result.length; i++) result[i] = (String)vector.elementAt(i);
        return result;
    }
	
	/**
	 *判断字符串数组中是否包含某字符串元素
	 *@param substring 某字符串
	 *@param source 源字符串数组
	 *@return 包含则返回true，否则返回false
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean in(String substring, String[] source)
	{
		if ((source == null) || (source.length ==0)) return false;
		HashSet hs = new HashSet(source.length);
		for (int i = 0 ; i < source.length ; i++)
		{
			hs.add(source[i]);
		}
		return hs.contains(substring);
	}

	  /**
	   * 获得主键
	   * @return String
	   */
	  public static String getPrimaryKey() {
	    Date now = new Date();
	    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	    return dateformat.format(now) ;
	  }
	  
	  
	  /**
	   * 获得主键 按索引


	   * @return String
	   */
	  public static String getPrimaryKey(int index) {
	    Date now = new Date();
	    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	    String indexAppendZero = NumberUtil.appendZero(index, 4);
	    return dateformat.format(now) + indexAppendZero + getRandomChar(9 - indexAppendZero.length());
	  }

	  /**
	   * 获得0-9,a-z,A-Z范围的随机数
	   *
	   * @param length 随机数长度


	   * @return String
	   */

	  public static String getRandomChar(int length) {
	    char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
	        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

	    Random random = new Random();
	    StringBuffer buffer = new StringBuffer();
	    for (int i = 0; i < length; i++) {
	      buffer.append(chr[random.nextInt(62)]);
	    }
	    return buffer.toString();
	  }

	  /**
	   * 获得10位随机字符


	   * @return String
	   */
	  public static String getRandomChar() {
	    return getRandomChar(10);
	  }

	  /**
	   * 判断字符是否为空
	   *
	   * @param input 某字符串
	   * @return 包含则返回true，否则返回false
	   */
	  public static boolean isEmpty(String input) {
	    return input == null || input.length() == 0;
	  }
	  /**
	   * 判断字符串数组中是否包含某字符串元素
	   *
	   * @param substring 某字符串
	   * @param source    源字符串数组
	   * @return 包含则返回true，否则返回false
	   */
	  public static boolean isIn(String substring, String[] source) {
	    if (source == null || source.length == 0) {
	      return false;
	    }
	    for (String aSource : source) {
	      if (aSource.equals(substring)) {
	        return true;
	      }
	    }
	    return false;
	  }
	  
	  
	  /**
	   * 判断字符串数组中是否包含某字符串元素
	   *
	   * @param titlestr 字符串

	   * @param length    定义的长度

	   * @return 返回截取后的字符
	   */
	  static public String subTitleStr(String titlestr,int length) {
			String str = titlestr;
			if(str.length()>length){
				str = str.substring(0,length)+"...";
			}
			return str;
	  }
		/**
		 * 得到客户端IP
		 * @param request
		 * @return
		 */
		public static String getClientIp(HttpServletRequest request){
			String ip = request.getHeader("X-Forwarded-For");
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("WL-Proxy-Client-IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("HTTP_CLIENT_IP");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	        }
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getRemoteAddr();
	        }
	        return ip;
		}
		public static String HtmlToEn(String s)
		  {
		    String s1 = "";
		    s1 = replace(s, "<", "&lt;");
		    s1 = replace(s1, ">", "&gt;");
		    s1 = replace(s1, "\r\n", "<br/>");
		    s1 = replace(s1, "\n", "<br/>");
		    s1 = replace(s1, " ", "&nbsp;&nbsp;");
		    s1 = replace(s1, "——", "#$");
		    return s1;
		  }

		  public static String HtmlToCn(String s)
		  {
			if(StringUtil.isEmpty(s)){
				return "";
			}
			else{
		    String s1 = "";
		    s1 = replace(s, "&lt;", "<");
		    s1 = replace(s1, "&gt;", ">");
		    s1 = replace(s1, "<br/>", "\r\n");
		    s1 = replace(s1, "&nbsp;&nbsp;", " ");
		    s1 = replace(s1, "#$", "——");
		    return s1;
			}
		  }
		  public static String[] randStrs(String[] date,int num){
			  System.out.println("num:"+num);
			  String[] returnStr =new String[num];
			  Random r = new Random();
		        int irdm = 0;
		        for(int i = 0; i < num; i ++) {
		            irdm = r.nextInt(date.length - i);
		            returnStr[i]=date[irdm];
		            for(int j = irdm; j < date.length- i - 1; j ++) {
		            	date[j] = date[j + 1];
		            }
		        }
		      return returnStr;
		  }
		  public static void main(String[] args) {
		        String[] data1 = {"5d7214ec-12de-4a00-903b-e1f768330561", "571392aa-9cad-42b8-ba5e-cfe8c5f1f95a","bf62797b-c1bf-4ae2-9eec-8af3aaeb1d15","a300cc99-7072-4f4b-b1e2-3e0f5c9a3bbb", "9c3fd685-e4e4-4c03-99b2-d4ba981483c0","022d4d62-0633-4f86-bd27-8febb01dc084","457b81d3-101f-4ec4-bd0d-805f427b4e65"};
		        String[] strs=randStrs(data1,2);
		        System.out.println("+++++++++++++++"+strs.length);
		    }
}